package com.me.template4j.util.encrypt;

import com.me.template4j.util.CommonUtil;

import java.util.Random;
import java.util.UUID;

/**
 * 复杂的加密类 uuid + ascii
 * @Authhor: qiu
 * @Date: 2022/12/14 3:08 下午
 */

public class AsciiEncrypt implements Encrypt {

    //ascii转换游标标识  标识更改后 记得数据库密码会对不上，需要重新设置
    private static final int  flag = 1;

    @Override
    public String encoded(String str) {

        StringBuffer psw = new StringBuffer();

        //循环解析数量 1-9
        int loopNum = new Random().nextInt(5)+1;

        //循环数字用base64转换
        String loopNumStr = new CommonUtil().encodedStrToBase64(String.valueOf(loopNum));

        String temp = str;
        for (int i = 0; i < loopNum; i++) {
            String encodedTemp = this.asciiEncoded(temp, flag);
            temp = encodedTemp;
        }

        String uuid = UUID.nameUUIDFromBytes(temp.getBytes()).toString().replace("-","");

        //uuid + loop  用感叹号分割
        psw.append(uuid).append("$").append(loopNumStr).append("!").append(temp);

        return psw.toString();
    }

    @Override
    public String decoded(String str) {

        //如果字符串都是空的，那么就是说明不符合密码规则
        if(str.contains("!")) {

            //数字循环部分
            String loopNumPart = str.substring(str.indexOf("$")+1 ,str.indexOf("!"));

            //密文真实内容部分
            String pswStrPart = str.substring(str.indexOf("!")+1);

            //得到循环数 用base64函数解码
            String loopNumStr = new CommonUtil().decodedBase64ToStr(loopNumPart);
            //判断是否为数字
            if(CommonUtil.isNumber(loopNumStr)) {
                String pswStr = pswStrPart;

                String temp = pswStr;
                for (int i = 0; i < Integer.parseInt(loopNumStr); i++) {
                    String encodedTemp = this.asciiEncoded(temp, -flag);
                    temp = encodedTemp;
                }

                return temp;
            }
        }

        return "";
    }

    @Override
    public boolean compare(String psw1, String psw2) {

        String decoded1 = this.decoded(psw1);
        String decoded2 = psw2;

        return decoded1.equals(decoded2);
    }


    /**
     * ascii 加密解密
     * @param str
     * @param flag +1 ascii都加  -1 都减
     * @return
     */
    private String asciiEncoded(String str, int flag) {
        StringBuffer buffer = new StringBuffer(str);
        for (int i = 0; i < str.length(); i++) {
            buffer.setCharAt(i,(char)(str.charAt(i)+flag));
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        String encoded = new AsciiEncrypt().encoded("123");
        System.out.println(encoded);
    }
}
